package com.test.dao;

import com.test.entity.Clazz;
import com.test.entity.Student;
import com.test.utils.DBUtil;
import org.hibernate.*;
import org.hibernate.query.Query;

import java.util.List;

public class StudentDAO {
    private Session session;
    private static StudentDAO instance;

    private StudentDAO() {}

    public static StudentDAO getInstance() {
        if (instance == null) {
            instance = new StudentDAO();
            instance.session = DBUtil.getSession();
        }

        return instance;
    }

    public List<Student> queryAll() {
        String hql = "from Student";
        Query query = session.createQuery(hql);
        return query.list();
    }

    public void insert(Student student) {
        Transaction tx = session.beginTransaction();
        session.save(student);
        tx.commit();
    }

    private void delete(String sno) {
        Student s = session.get(Student.class, sno);
        if(s != null) {
            Transaction tx = session.beginTransaction();
            session.delete(s);
            tx.commit();
        }
    }

    public Student selectBySno(String sno) {
        return session.load(Student.class, sno);
    }
    public static void main(String[] args) {
        StudentDAO dao = StudentDAO.getInstance();
        Student s = new Student();
        s.setSno("10001");
        s.setName("张三");
        s.setAddr("武汉市");
        s.setSex("男");
        s.setRemark("优秀学生");
        s.setQq("1234567890");
        Clazz c = new Clazz();
        c.setCid(1);
        s.setTbClassByCid(c);
        s = dao.selectBySno("10001");
    }
}
